from typing import Optional, Dict, List, Any
from contextlib import AsyncExitStack

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import logging
#from anthropic import Anthropic
#from dotenv import load_dotenv
import json
from core.providers import provider

logger = logging.getLogger("weather.SimpleMCPClient")
class SimpleMCPClient:
    def __init__(self, server_name, command, models_cfg, args=None, env=None):
        self.server_name = server_name
        self.command = command
        self.args = args or []
        self.tools = []
        self.session: Optional[ClientSession] = None
        self.exit_stack = AsyncExitStack()

        self.models_cfg = models_cfg

    async def start(self):
        """
        Connect to an Simple MCP server
        
        Args:
            server_script_path: Path to the server script (.py or .js)
        """
            
        server_params = StdioServerParameters(
            command=self.command,
            args=self.args,
            env=None
        )
        #print(server_params)
        stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
        self.stdio, self.write = stdio_transport
        self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
        
        await self.session.initialize()
        # List available tools
        response = await self.session.list_tools()
        tools = response.tools
        self.tools=tools
        logger.info(f"Server {self.server_name}: Connected to server in start process with tools: {[tool.name for tool in tools]}")

    async def create_model(self, provider_name: str):
        self.model=provider.Provider(self.models_cfg).create(provider_name)
    def create_messages(self, query: str):
        # 4) Build conversation
        # Get system message - either from systemMessageFile, systemMessage, or default
        conversation = []
        chosen_model=self.models_cfg
        system_msg = "You are a weather forecast assistant with ability to use tool function call according to location or geographical coordinates."
        if "systemMessageFile" in chosen_model:
            try:
                with open(chosen_model["systemMessageFile"], "r", encoding="utf-8") as f:
                    system_msg = f.read()
            except Exception as e:
                logger.warning(f"Failed to read system message file: {e}")
                # Fall back to direct systemMessage if available
                conversation.append({"role": "system", "content": chosen_model.get("systemMessage", system_msg)})
        else:
            conversation.append({"role": "system", "content": chosen_model.get("systemMessage", system_msg)})
        if "systemMessageFiles" in chosen_model:
            for file in chosen_model["systemMessageFiles"]:
                try:
                    with open(file, "r", encoding="utf-8") as f:
                        system_msg = f.read()
                        conversation.append({"role": "system", "content": "File: " + file + "\n" + system_msg})
                except Exception as e:
                    logger.warning(f"Failed to read system message file: {e}")
 
        conversation.append({"role": "user", "content": query})
        return conversation
    async def process_query(self, query: str) -> str:
        """Process a query using Claude and available tools"""
        messages = [
            {
                "role": "user",
                "content": query
            }
        ]

        # gather tools with type mcp.Tool
        all_functions = []
        logger.info(f"Server {self.server_name}: Gather tools in process query...")
        for t in self.tools:
            input_schema = t.inputSchema or {"type": "object", "properties": {}}
            fn_def = {
                "name": t.name,
                "description": t.description,
                "parameters": input_schema
            }
            all_functions.append(fn_def)
       
        #logger.info(f"Server {self.server_name}: list all_function info {json.dumps(all_functions, indent=2)}")

        # Initial Claude API call
        """
        response = self.anthropic.messages.create(
            #model="claude-3-5-sonnet-20241022",
            model="qwen3:0.6b",
            max_tokens=1000,
            messages=messages,
            tools=available_tools
        )
        """
        conversation=self.create_messages(query)
        response=await self.model.generate_response(
            conversation,
            all_functions=all_functions
        )
        # Process response and handle tool calls
        final_text = []

        for content in response.content:
            logger.info(f"response content is {content}")
            if content.type == 'text':
                final_text.append(content.text)
            elif content.type == 'tool_use':
                tool_name = content.name
                arguments = content.input
                
                # Execute tool call
                result = await self.session.call_tool(tool_name, arguments)
                logger.info(f"[Calling tool={tool_name} with arguments={arguments}] with result {result}")
                final_text.append(f"[Calling tool {tool_name} with args {arguments}]")

                # Continue conversation with tool results
                if hasattr(content, 'text') and content.text:
                    messages.append({
                      "role": "assistant",
                      "content": content.text
                    })
                messages.append({
                    "role": "user", 
                    "content": result.content[0].text
                })
                # Get next response from Claude
                response = await self.model.generate_response(
                    messages, 
                    all_functions=None,
                    max_round=1,
                )

                final_text.append(response.content[0].text)

        return "\n".join(final_text)
        
    async def chat_loop(self):
        """Run an interactive chat loop"""
        print("\nMCP Client Started!")
        print("Type your queries or 'quit' to exit.")
        
        while True:
            try:
                query = input("\nQuery: ").strip()
                
                if query.lower() == 'quit':
                    break
                    
                response = await self.process_query(query)
                print("\n" + response)
                    
            except Exception as e:
                print(f"\nError: {str(e)}")
    
    async def cleanup(self):
        """Clean up resources"""
        await self.exit_stack.aclose()
